#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <string>
#include "RingQueue.hpp"
#include "Task.hpp"

using namespace std;

struct ThreadData
{
    RingQueue<Task>* _rq;
    string _thread_name;
};

void* Consumer(void* args)
{
    ThreadData *td = static_cast<ThreadData*>(args);
    RingQueue<Task> *rq = td->_rq;
    std::string name = td->_thread_name;

    while (true)
    {
         // 1. 消费数据
        Task t;
        rq->Pop(&t);
       
        // 2. 处理数据
        t();
        cout << "Consumer get task, task is : " << t.GetTask() << " who: " << name << " result: " << t.GetRes() << endl;
        sleep(1);
    }
    return nullptr;
    
}

void* Productor(void* args)
{    
    ThreadData *td = static_cast<ThreadData*>(args);
    RingQueue<Task> *rq = td->_rq;
    std::string name = td->_thread_name;
    int len = OP.size();

    while (true)
    {   
        //1、获取数据
        int data1 = rand() % 10 + 1;
        usleep(10);
        int data2 = rand() % 10;
        char op = OP[rand() % len];
        Task t(data1, data2, op);
        //生产数据
        rq->Push(t);
        cout << "Product a task is :" << t.GetTask() << "who :" << name << endl;
        //sleep(1); //当运行起来后，生产者会把环形队列数据填满。
                    //然后消费者消费一个后，生产者紧跟着继续生产。
    }
        return nullptr;
    }

int main()
{
    srand(time(nullptr) ^ getpid());//种一颗随机数种子  
    RingQueue<Task>* rq = new RingQueue<Task>();


    pthread_t c[3],p[5]; //生产者和消费者
    //创建新线程
    
    for(int i = 0; i < 3; i++)
    {
        ThreadData * td = new ThreadData();
        td->_rq = rq;
        td->_thread_name = "thread-" + to_string(i);
        pthread_create(c+i ,nullptr,Consumer,td);
    }

    for(int i = 0; i < 3; i++)
    {
        ThreadData * td = new ThreadData();
        td->_rq = rq;
        td->_thread_name = "thread-" + to_string(i);
        pthread_create(p+i,nullptr,Productor,td);
    }

    for(int i = 0; i < 3; i++)
        pthread_join(c[i],nullptr);
    
    for(int i = 0; i < 3; i++)
        pthread_join(p[i],nullptr);

    return 0;
}